<template>
  <div class="my-assignments-container">
    <el-card class="assignments-card">
      <template #header>
        <div class="card-header">
          <h2>我的接单</h2>
          <el-button type="primary" @click="refreshAssignmentList" :loading="loading">
            <el-icon><Refresh /></el-icon>刷新列表
          </el-button>
        </div>
      </template>
      
      <!-- 状态筛选按钮组 -->
      <div class="filter-row">
        <div class="status-buttons">
          <el-button 
            :type="activeStatus === 'all' ? 'primary' : 'default'"
            @click="handleStatusChange('all')"
          >
            全部接单
          </el-button>
          <el-button 
            :type="activeStatus === 'pending' ? 'primary' : 'default'"
            @click="handleStatusChange('pending')"
          >
            待发货
          </el-button>
          <el-button 
            :type="activeStatus === 'shipping' ? 'primary' : 'default'"
            @click="handleStatusChange('shipping')"
          >
            运输中
          </el-button>
          <el-button 
            :type="activeStatus === 'delivered' ? 'primary' : 'default'"
            @click="handleStatusChange('delivered')"
          >
            已送达
          </el-button>
          <el-button 
            :type="activeStatus === 'signed' ? 'primary' : 'default'"
            @click="handleStatusChange('signed')"
          >
            已签收
          </el-button>
        </div>
        
        <!-- 搜索框 -->
        <div class="search-input">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索订单号或客户姓名" 
            clearable
            @keyup.enter="handleSearch"
            style="width: 250px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
      
      <!-- 配送记录列表 -->
      <div class="assignment-list" v-if="assignmentList.length > 0">
        <div class="assignment-item" v-for="assignment in assignmentList" :key="assignment.assignmentId">
          <div class="assignment-header">
            <div class="order-info">
              <strong>{{ assignment.orderNumber }}</strong>
              <el-tag :type="getStatusType(assignment.status)" size="small">
                {{ getStatusText(assignment.status) }}
              </el-tag>
            </div>
            <div class="assignment-time">
              接单时间：{{ formatDateTime(assignment.assignedAt) }}
            </div>
          </div>
          
          <div class="assignment-content">
            <div class="customer-info">
              <div class="sender-info">
                <div class="info-label">
                  <el-icon><User /></el-icon>
                  寄件人
                </div>
                <div class="info-content">
                  <div class="contact">{{ assignment.senderName }}</div>
                </div>
              </div>
              
              <div class="receiver-info">
                <div class="info-label">
                  <el-icon><LocationFilled /></el-icon>
                  收件人
                </div>
                <div class="info-content">
                  <div class="contact">{{ assignment.receiverName }}</div>
                  <div class="address">{{ assignment.receiverAddress }}</div>
                </div>
              </div>
            </div>
            
            <div class="assignment-remark" v-if="assignment.remark">
              <div class="remark-label">接单备注：</div>
              <div class="remark-content">{{ assignment.remark }}</div>
            </div>
            
            <div class="completion-info" v-if="assignment.completedAt">
              <div class="completion-time">
                完成时间：{{ formatDateTime(assignment.completedAt) }}
              </div>
            </div>
          </div>
          
          <div class="assignment-footer">
            <div class="assignment-actions">
              <el-button size="small" @click="viewOrderDetail(assignment.orderId)">
                查看订单详情
              </el-button>
              <el-button 
                v-if="assignment.status === 1" 
                type="primary" 
                size="small"
                @click="startDelivery(assignment)"
                :loading="updatingAssignmentId === assignment.assignmentId"
              >
                开始发货
              </el-button>
              <el-button 
                v-if="assignment.status === 2" 
                type="success" 
                size="small"
                @click="goToDeliveryManagement(assignment)"
              >
                去配送
              </el-button>
              <el-button 
                v-if="assignment.status === 3" 
                type="success" 
                size="small"
                @click="markSigned(assignment)"
                :loading="updatingAssignmentId === assignment.assignmentId"
              >
                标记签收
              </el-button>
              <el-button 
                v-if="assignment.status === 4" 
                type="info" 
                size="small"
                disabled
              >
                已签收
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <!-- 空状态 -->
      <div class="empty-placeholder" v-if="assignmentList.length === 0 && !loading">
        <el-empty description="暂无接单记录">
          <el-button type="primary" @click="$router.push('/availableOrders')">
            去接单
          </el-button>
        </el-empty>
      </div>
      
      <!-- 加载状态 -->
      <div class="loading" v-if="loading">
        <el-skeleton :rows="3" animated />
      </div>
    </el-card>
    
    <!-- 配送状态更新对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetStatusForm"
    >
      <div class="status-dialog-content">
        <div class="assignment-summary">
          <h4>配送信息</h4>
          <p>订单号：{{ selectedAssignment?.orderNumber }}</p>
          <p>收件人：{{ selectedAssignment?.receiverName }}</p>
          <p>收件地址：{{ selectedAssignment?.receiverAddress }}</p>
        </div>
        
        <el-form :model="statusForm" label-width="80px">
          <el-form-item label="状态备注">
            <el-input
              v-model="statusForm.remark"
              type="textarea"
              :placeholder="statusForm.placeholder"
              :rows="3"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStatusUpdate" :loading="updatingStatus">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 订单详情模态框 -->
    <OrderDetailModal
      v-model:visible="orderDetailVisible"
      :order-id="selectedOrderId"
      :show-start-delivery-btn="false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Refresh, User, LocationFilled } from '@element-plus/icons-vue'
import { courierApi, type DeliveryAssignment } from '@/api/courier'
import { ElMessage, ElMessageBox } from 'element-plus'
import OrderDetailModal from './components/OrderDetailModal.vue'

const router = useRouter()
const activeStatus = ref('all')
const searchKeyword = ref('')
const assignmentList = ref<DeliveryAssignment[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 状态更新相关
const statusDialogVisible = ref(false)
const selectedAssignment = ref<DeliveryAssignment | null>(null)
const statusForm = ref({
  remark: '',
  placeholder: ''
})
const updatingStatus = ref(false)
const updatingAssignmentId = ref<number | null>(null)
const dialogTitle = ref('')

// 订单详情相关
const orderDetailVisible = ref(false)
const selectedOrderId = ref<number | null>(null)

// 获取我的配送记录
const getMyAssignments = async () => {
  loading.value = true
  try {
    console.log('开始获取配送记录')
    const response = await courierApi.getMyAssignments(currentPage.value, pageSize.value)
    console.log('配送记录响应:', response)
    
    if (response.code === 200) {
      let list = response.data.list || []
      
      // 根据状态筛选
      if (activeStatus.value !== 'all') {
        const statusMap = {
          'pending': 1,    // 待发货
          'shipping': 2,   // 运输中
          'delivered': 3,  // 已送达
          'signed': 4      // 已签收
        }
        const filterStatus = statusMap[activeStatus.value as keyof typeof statusMap]
        list = list.filter(item => item.status === filterStatus)
      }
      
      // 根据关键词搜索
      if (searchKeyword.value.trim()) {
        const keyword = searchKeyword.value.trim().toLowerCase()
        list = list.filter(item => 
          item.orderNumber.toLowerCase().includes(keyword) ||
          item.senderName.toLowerCase().includes(keyword) ||
          item.receiverName.toLowerCase().includes(keyword)
        )
      }
      
      assignmentList.value = list
      total.value = response.data.total || 0
      console.log('获取到配送记录数量:', assignmentList.value.length)
    } else {
      console.error('获取配送记录失败，响应码:', response.code)
      ElMessage.error(response.message || '获取配送记录失败')
      assignmentList.value = []
      total.value = 0
    }
  } catch (error: any) {
    console.error('获取配送记录异常:', error)
    ElMessage.error('获取配送记录失败')
    assignmentList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 刷新配送记录列表
const refreshAssignmentList = () => {
  getMyAssignments()
}

// 处理状态切换
const handleStatusChange = (status: string) => {
  activeStatus.value = status
  currentPage.value = 1
  getMyAssignments()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  getMyAssignments()
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  activeStatus.value = 'all'
  currentPage.value = 1
  getMyAssignments()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getMyAssignments()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getMyAssignments()
}

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  selectedOrderId.value = orderId
  orderDetailVisible.value = true
}

// 开始发货
const startDelivery = (assignment: DeliveryAssignment) => {
  // 跳转到配送管理页面，携带订单ID和配送记录ID参数，并指定打开轨迹管理
  router.push({
    path: '/delivery-management',
    query: {
      orderId: assignment.orderId.toString(),
      assignmentId: assignment.assignmentId.toString(),
      action: 'manage-track', // 修改action为manage-track
      autoOpen: 'true' // 添加自动打开标识
    }
  })
}

// 去配送管理
const goToDeliveryManagement = (assignment: DeliveryAssignment) => {
  // 直接跳转到配送管理页面
  router.push('/delivery-management')
}

// 标记送达
const markDelivered = (assignment: DeliveryAssignment) => {
  selectedAssignment.value = assignment
  dialogTitle.value = '标记送达'
  statusForm.value.placeholder = '请输入送达备注（可选）'
  statusDialogVisible.value = true
}

// 标记签收
const markSigned = (assignment: DeliveryAssignment) => {
  selectedAssignment.value = assignment
  dialogTitle.value = '标记签收'
  statusForm.value.placeholder = '请输入签收备注（可选）'
  statusDialogVisible.value = true
}

// 确认状态更新
const confirmStatusUpdate = async () => {
  if (!selectedAssignment.value) return
  
  updatingStatus.value = true
  updatingAssignmentId.value = selectedAssignment.value.assignmentId
  
  try {
    console.log('更新配送状态:', {
      assignmentId: selectedAssignment.value.assignmentId,
      currentStatus: selectedAssignment.value.status,
      newStatus: selectedAssignment.value.status + 1,
      remark: statusForm.value.remark
    })
    
    let response: any
    
    if (selectedAssignment.value.status === 1) {
      // 开始发货：从待发货(1)到运输中(2)
      response = await courierApi.startDelivery(
        selectedAssignment.value.assignmentId,
        statusForm.value.remark
      )
    } else if (selectedAssignment.value.status === 3) {
      // 标记送达：从已送达(3)到待签收(4)
      response = await courierApi.updateDeliveryStatus(
        selectedAssignment.value.assignmentId,
        4,
        statusForm.value.remark
      )
    } else if (selectedAssignment.value.status === 4) {
      // 标记签收：从待签收(4)到已签收(5)
      response = await courierApi.updateDeliveryStatus(
        selectedAssignment.value.assignmentId,
        5,
        statusForm.value.remark
      )
    }
    
    console.log('状态更新响应:', response)
    
    if (response.code === 200) {
      ElMessage.success('状态更新成功！')
      statusDialogVisible.value = false
      // 刷新列表
      getMyAssignments()
    } else {
      console.error('状态更新失败，响应码:', response.code)
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error: any) {
    console.error('状态更新请求异常:', error)
    console.error('错误详情:', {
      message: error.message,
      code: error.code,
      response: error.response
    })
    
    if (error.code === 400) {
      ElMessage.error(error.message || '配送状态不正确，无法更新')
    } else if (error.code === 404) {
      ElMessage.error('配送记录不存在')
    } else if (error.code === 401) {
      ElMessage.error('用户未登录，请先登录')
    } else if (error.message) {
      ElMessage.error(`状态更新失败: ${error.message}`)
    } else {
      ElMessage.error('状态更新失败，请稍后重试')
    }
  } finally {
    updatingStatus.value = false
    updatingAssignmentId.value = null
  }
}

// 重置状态表单
const resetStatusForm = () => {
  statusForm.value.remark = ''
  statusForm.value.placeholder = ''
  selectedAssignment.value = null
}

// 获取状态文本
// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: '待揽收',
    1: '待发货',
    2: '运输中',
    3: '已送达',
    4: '已签收'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status: number) => {
  const typeMap: { [key: number]: string } = {
    0: 'danger',
    1: 'warning',
    2: 'primary',
    3: 'info',
    4: 'success'
  }
  return typeMap[status] || 'default'
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('我的接单页面已挂载')
  getMyAssignments()
})
</script>

<style scoped>
.my-assignments-container {
  padding: 20px;
}

.assignments-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.status-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-shrink: 0;
}

.assignment-list {
  margin-bottom: 20px;
}

.assignment-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  transition: all 0.3s;
}

.assignment-item:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.assignment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.assignment-time {
  font-size: 14px;
  color: #999;
}

.assignment-content {
  margin-bottom: 12px;
}

.customer-info {
  margin-bottom: 12px;
}

.sender-info, .receiver-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  gap: 12px;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 70px;
  font-weight: 500;
  color: #666;
}

.info-content {
  flex: 1;
}

.contact {
  font-weight: 500;
  margin-bottom: 2px;
}

.address {
  color: #666;
  font-size: 14px;
}

.assignment-remark {
  display: flex;
  gap: 8px;
  font-size: 14px;
  color: #666;
  background: #f0f9ff;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #3b82f6;
  margin-bottom: 8px;
}

.remark-label {
  font-weight: 500;
  min-width: 80px;
}

.completion-info {
  background: #f0f9ff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  color: #666;
}

.assignment-footer {
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.assignment-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.pagination {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.empty-placeholder {
  margin: 60px 0;
}

.loading {
  margin: 20px 0;
}

.status-dialog-content {
  padding: 10px 0;
}

.assignment-summary {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.assignment-summary h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.assignment-summary p {
  margin: 6px 0;
  color: #666;
}

@media (max-width: 1200px) {
  .filter-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-input {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .assignment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .assignment-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .status-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>